package com.xm.pattern.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class Proxy implements InvocationHandler {
    private Object object;

    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }

    public Proxy(Object _object) {
        this.object = _object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        this.before();
        try {
            return method.invoke(this.object, args);
        } catch (Exception e) {
            throw e;
        } finally {
            this.after();
        }
    }

    public static <T> T newInstance(T _object) {
        return (T) java.lang.reflect.Proxy.newProxyInstance(_object.getClass().getClassLoader(), _object.getClass().getInterfaces(), new Proxy(_object));
    }
}
